import { all, call, put, takeLatest } from "redux-saga/effects";
import { Creators as AskCreators } from "redux/actions/ask";
import { AskTypes } from "redux/constants";
import { api } from "redux/api";
import interceptResponse from "redux/api/interceptResponse";
import interceptError from "redux/api/interceptError";

function* askList({ payload }) {
  try {
    const { page, limit } = payload;
    const response = yield call(
      api.get,
      `/api/questions/?page=${page}&limit=${limit}`
    );
    yield interceptResponse(response);
    if (response.data?.code !== 1000) {
      throw response;
    }
    yield put(AskCreators.listSuccess(response.data));
  } catch (err) {
    yield interceptError(AskCreators.listFailure, err);
  }
}

function* askPublish({ payload }) {
  try {
    const { token, title, content } = payload;
    yield call(api.setHeader, "Authorization", `Bearer ${token}`);
    const response = yield call(api.post, `/api/question`, {
      question_caption: title,
      question_content: content,
    });
    yield interceptResponse(response);
    if (response.data?.code !== 1000) {
      throw response;
    }
    // console.log("request success response===>", response.data);
    yield put(AskCreators.publishSuccess(response.data));
    yield call(Router.replace, { pathname: "/" });
  } catch (err) {
    yield interceptError(AskCreators.publishFailure, err);
  }
}

function* askDetail({ payload }) {
  try {
    const { sn } = payload;
    const response = yield call(api.get, `/api/question?question_id=${sn}`);
    yield interceptResponse(response);
    if (response.data?.code !== 1000) {
      throw response;
    }
    yield put(AskCreators.detailSuccess(response.data));
  } catch (err) {
    yield interceptError(AskCreators.detailFailure, err);
  }
}

function* askEdit({ payload }) {
  try {
    const { token, sn, title, content } = payload;
    yield call(api.setHeader, "Authorization", `Bearer ${token}`);
    const response = yield call(
      api.post,
      `/api/question/edit?question_id=${sn}`,
      {
        title: title,
        content: content,
      }
    );
    yield interceptResponse(response);
    if (response.data?.code !== 1000) {
      throw response;
    }
    yield put(AskCreators.editSuccess(response.data));
  } catch (err) {
    yield interceptError(AskCreators.editFailure, err);
  }
}

export default function* () {
  yield all([
    takeLatest(AskTypes.QUESTION_LIST_REQUEST, askList),
    takeLatest(AskTypes.QUESTION_PUBLISH_REQUEST, askPublish),
    takeLatest(AskTypes.QUESTION_DETAIL_REQUEST, askDetail),
    takeLatest(AskTypes.QUESTION_EDIT_REQUEST, askEdit),
  ]);
}
